package com.bing.client;

import com.bing.common.Message;
import com.bing.common.MessageType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;

/**
 * 客户端消息处理器
 */
public class ClientHandler extends SimpleChannelInboundHandler<Message> {

    private final ChatClient chatClient;

    public ClientHandler(ChatClient chatClient) {
        this.chatClient = chatClient;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        chatClient.setConnected(true);
        System.out.println("成功连接到服务器！");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        chatClient.setConnected(false);
        chatClient.setLoggedIn(false);
        System.out.println("与服务器的连接已断开。");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) {
        try {
            System.out.println("收到服务器消息: 类型=" + msg.getType() + ", 内容=" + msg.getContent());

            switch (msg.getType()) {
                case LOGIN_RESPONSE:
                    handleLoginResponse(msg);
                    break;
                case REGISTER_RESPONSE:
                    handleRegisterResponse(msg);
                    break;
                case CHAT_MESSAGE:
                    handleChatMessage(msg);
                    break;
                case SYSTEM_MESSAGE:
                    handleSystemMessage(msg);
                    break;
                case HISTORY_RESPONSE:
                    handleHistoryResponse(msg);
                    break;
                case UPDATE_INFO_RESPONSE:
                    handleUpdateInfoResponse(msg);
                    break;
                default:
                    System.out.println("收到未知类型消息: " + msg.getType());
                    break;
            }
        } catch (Exception e) {
            System.err.println("处理消息时发生异常: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 处理登录响应
     */
    private void handleLoginResponse(Message msg) {
        String content = msg.getContent();
        System.out.println("处理登录响应: " + content);

        // 检查响应内容是否以"true"开头
        if (content != null && content.startsWith("true")) {
            chatClient.setLoggedIn(true);
            System.out.println("登录成功！");
        } else {
            // 提取错误信息
            String errorMsg = "未知错误";
            if (content != null && content.contains("|")) {
                errorMsg = content.split("\\|")[1];
            }
            System.out.println("登录失败：" + errorMsg);
        }
    }

    /**
     * 处理注册响应
     */
    private void handleRegisterResponse(Message msg) {
        String content = msg.getContent();
        System.out.println("处理注册响应: " + content);

        // 检查响应内容是否以"true"开头
        if (content != null && content.startsWith("true")) {
            System.out.println("注册成功，请登录");
        } else {
            // 提取错误信息
            String errorMsg = "未知错误";
            if (content != null && content.contains("|")) {
                errorMsg = content.split("\\|")[1];
            }
            System.out.println("注册失败：" + errorMsg);
        }
    }

    /**
     * 处理聊天消息
     */
    private void handleChatMessage(Message msg) {
        String sender = msg.getSender();
        String content = msg.getContent();
        String receiver = msg.getReceiver();

        if (receiver != null && !receiver.isEmpty()) {
            // 私聊消息
            if (sender.equals(chatClient.getUsername())) {
                System.out.println("[私聊] 你对 " + receiver + " 说: " + content);
            } else {
                System.out.println("[私聊] " + sender + " 对你说: " + content);
            }
        } else {
            // 公共消息
            System.out.println("[公共] " + sender + ": " + content);
        }
    }

    /**
     * 处理系统消息
     */
    private void handleSystemMessage(Message msg) {
        System.out.println("[系统] " + msg.getContent());
    }

    /**
     * 处理历史消息响应
     */
    private void handleHistoryResponse(Message msg) {
        List<Message> history = msg.getHistoryMessages();
        System.out.println("==== 历史消息 ====");
        if (history != null && !history.isEmpty()) {
            for (Message historyMsg : history) {
                String sender = historyMsg.getSender();
                String content = historyMsg.getContent();
                String time = historyMsg.getSendTime() != null ? historyMsg.getSendTime().toString() : "未知时间";
                System.out.println("[" + time + "] " + sender + ": " + content);
            }
        } else {
            System.out.println("暂无历史消息");
        }
        System.out.println("================");
    }

    /**
     * 处理更新用户信息响应
     */
    private void handleUpdateInfoResponse(Message msg) {
        String content = msg.getContent();
        System.out.println("处理用户信息更新响应: " + content);

        // 检查响应内容是否以"true"开头
        if (content != null && content.startsWith("true")) {
            String successMsg = "更新用户信息成功！";
            if (content.contains("|")) {
                successMsg = content.split("\\|")[1];
            }
            System.out.println(successMsg);

            // 如果更新了用户名，同步更新客户端的用户名
            if (msg.getReceiver() != null) {
                chatClient.setUsername(msg.getReceiver());
            }
        } else {
            // 提取错误信息
            String errorMsg = "未知错误";
            if (content != null && content.contains("|")) {
                errorMsg = content.split("\\|")[1];
            }
            System.out.println("更新用户信息失败：" + errorMsg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.err.println("ClientHandler异常: " + cause.getMessage());
        cause.printStackTrace();
        ctx.close();
    }
}